﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.DataAccess;
using System.Data;
using YiYiTong.Rocket.EFDBFirst;
using YiYiTong.Rocket.Business.Biz;
using System.Text.RegularExpressions;

namespace YiYiTong.Rocket.Business
{
    public class OrderBiz
    {
        #region 单例模式
        private OrderBiz()
        {
        }

        private static OrderBiz _instance;
        private static readonly object _syncObject = new object();

        public static OrderBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new OrderBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 单例模式

        #region 充值订单
        /// <summary>
        /// 创建充值订单
        /// </summary>
        /// <returns></returns>
        public bool CreateChargeOrder(string orderId, string billNo, long uid, int business_order_type, long orderMasterId, decimal amt, int channelType, string remark)
        {
            if (string.IsNullOrEmpty(orderId) || string.IsNullOrEmpty(billNo) || uid <= 0 || amt <= 0)
            {
                LogHelper.Error("创建充值订单失败,方法参数错误");
                return false;
            }

            string orderResult = string.Empty;
            long orderRet = OrderDataAccess.Instance.CreateChargeOrder(orderId, billNo, uid, business_order_type, orderMasterId, amt, channelType, remark, out orderResult);
            if (orderRet > 0)
                return true;
            else
            {
                LogHelper.Error("创建充值订单失败：" + orderResult);
                return false;
            }
        }

        /// <summary>
        /// 充值订单更新-支付成功
        /// </summary>
        /// <returns></returns>
        public bool ChargeOrderSucc(string orderId, string sellOrderNo, decimal succAmt, out long order_master_id, out int business_order_type)
        {
            string stroutput = string.Empty;
            order_master_id = 0;
            business_order_type = 0;
            if (string.IsNullOrEmpty(orderId) || string.IsNullOrEmpty(sellOrderNo) || succAmt <= 0)
            {
                LogHelper.Error("充值订单更新失败,方法参数错误");
                return false;
            }

            int ret = OrderDataAccess.Instance.ChargeOrderSucc(orderId, sellOrderNo, succAmt, out order_master_id, out business_order_type, out stroutput);
            if (ret > 0)
                return true;
            else
            {
                LogHelper.Error("充值订单更新失败,原因：" + stroutput);
                return false;
            }
        }

        /// <summary>
        /// 充值订单更新-支付失败
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="sellErrorCode"></param>
        /// <param name="sellErrorMsg"></param>
        /// <returns></returns>
        public bool ChargeOrderFail(string orderId, string sellErrorCode, string sellErrorMsg)
        {
            string stroutput = string.Empty;
            if (string.IsNullOrEmpty(orderId) || string.IsNullOrEmpty(sellErrorCode) || string.IsNullOrEmpty(sellErrorMsg))
            {
                LogHelper.Error("充值订单更新失败,方法参数错误");
                return false;
            }

            int ret = OrderDataAccess.Instance.ChargeOrderFail(orderId, sellErrorCode, sellErrorMsg, out stroutput);
            if (ret > 0)
                return true;
            else
            {
                LogHelper.Error("充值订单更新失败,原因：" + stroutput);
                return false;
            }
        }
        #endregion

        #region 交易订单

        public void WriteOrderLog(ADZ_OrderMasterLog aDZ_OrderMasterLog)
        {
            try
            {
                Task.Run(() =>
                {
                    aDZ_OrderMasterLog.create_time = DateTime.Now;
                    ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                    dbcontext.ADZ_OrderMasterLog.Add(aDZ_OrderMasterLog);
                    dbcontext.SaveChanges();
                });
            }
            catch (Exception ex)
            {
                LogHelper.Error("记录订单日志：" + ex.GetExcetionMessage());
            }
        }
        /// <summary>
        /// 交易订单支付成功
        /// </summary>
        /// <param name="pay_type">2 余额 3 支付宝 4 微信</param>
        /// <returns></returns>
        public bool OrderPaySucc(long order_id, int pay_type)
        {
            try
            {
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                string stroutput = string.Empty;
                if (order_id <= 0)
                {
                    LogHelper.Error("交易订单更新失败,方法参数错误");
                    return false;
                }

                int ret = OrderDataAccess.Instance.OrderPaySucc(order_id, pay_type, out stroutput);
                if (ret > 0)
                {
                    var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == order_id);

                    //如果是竞价产生的订单，需要修改竞价状态
                    var jingjia_submit = dbcontext.ADZ_JingjiaSubmit.FirstOrDefault(t => t.order_master_id == order_master.order_id);
                    if (jingjia_submit != null)
                    {
                        jingjia_submit.status = 10;
                        dbcontext.SaveChanges();
                    }

                    //发送业务消息
                    BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                    {
                        BusinessMsgType = (int)BusinessMsgEnum.UserCreateOrder,
                        msg = $"订单支付成功，订单号{order_master.order_NO},订单金额：￥{order_master.total_money}",
                        msg_title = "订单支付成功",
                        msg_url = $"/OrderMaster/OrderMasterInfo/{order_master.order_id}"
                    });
                    //发送推送消息
                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "支付成功",
                            MsgText = $"您的订单{order_master.order_NO}已支付成功，本次付款金额：￥{order_master.total_money}，爱电子将尽快安排发货。"
                        },
                        ReceiveUids = order_master.uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(paramModel);

                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = order_id,
                        opmsg = "支付成功"
                    });

                    #region 改为订单创建成功扣除库存
                    ////开始处理商品库存
                    //List<OrderGood> list = OrderDataAccess.Instance.GetOrderGood(order_id);
                    //if (list != null && list.Count > 0)
                    //{
                    //    foreach (var item in list)
                    //    {
                    //        if (GoodsDataAccess.Instance.DeductStockAmount(item.goods_id, item.amount) <= 0)
                    //            LogHelper.Error("交易订单更新失败,原因：更新扣除库存失败" + JsonHelper.Serialize(new { goods_id = item.goods_id, amount = item.amount }));
                    //    }
                    //}
                    #endregion

                    //开始写入异步redis消息
                    //处理平台费用
                    var obj = new
                    {
                        orderid = order_id,
                        paytype = pay_type
                    };
                    RedisService.PrependItemToList(RedisKeys.OrderSettlementKey, JsonHelper.Serialize(obj));
                    return true;
                }
                else
                {
                    LogHelper.Error("交易订单更新失败,原因：" + stroutput);
                    return false;
                }
            }
            catch (Exception e)
            {
                LogHelper.Fatal("交易订单更新失败：" + e.GetExcetionMessage());
                return false;
            }
        }

        /// <summary>
        /// 平台费用写入
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> OrderSettlementWrite(long order_id)
        {
            if (order_id <= 0)
                return new Tuple<bool, string>(false, "订单不存在");

            string stroutput = string.Empty;
            int ret = OrderDataAccess.Instance.OrderSettlementWrite(order_id, out stroutput);
            if (ret > 0)
                return new Tuple<bool, string>(true, "");
            else
                return new Tuple<bool, string>(false, stroutput);
        }

        /// <summary>
        /// 创建预热转交易订单
        /// order_source 0 用户购物车下单 11 预订成功后系统下单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string, string> CreateYureOrder(long uid, int order_source, long place_id, CreateYureOrderReq model)
        {
            if (uid <= 0)
                return new Tuple<bool, string, string>(false, "", "用户不存在，无法下单");

            string stroutput = string.Empty;
            string orderno = Utils.BuildOrderId("", 20);
            string remark = string.Empty;
            string msg = string.Empty;
            if (order_source == 0)
                remark = "用户购物车下单";
            else if (order_source == 11)
                remark = "预订成功后系统下单";
            else
                return new Tuple<bool, string, string>(false, "", "订单来源错误，无法下单");

            var acc = AccountDataAccess.Instance.GetAccount(uid);
            if (acc == null)
                return new Tuple<bool, string, string>(false, "", "用户不存在，无法下单");

            //有价格商品才能下单（不管是直播还是预热商品）
            bool isBuild = false;
            foreach (var item in model.goodlist)
            {
                if (item.goods_id <= 0 || item.place_amount <= 0 || item.place_price <= 0)
                {
                    msg = "参数为空，无法下单";
                    break;
                }
                //验证商品信息
                var result = GoodsBiz.Instance.GetGoods(item.goods_id);
                if (result.Item1)
                {
                    if (item.place_amount > result.Item2.stock_amount)
                    {
                        msg = "此商品库存不足，无法下单";
                        break;
                    }
                    if (item.place_amount < result.Item2.min_amount)
                    {
                        msg = "此商品购买数量不能低于最小出库量，无法下单";
                        break;
                    }

                    //增加美元业务判断 by leev 2019-04-01
                    if (result.Item2.currency_type == (int)CurrencyType.Dollar)
                    {
                        msg = "美元业务价格面议，无法下单";
                        break;
                    }

                    isBuild = true;
                    model.total_money = item.place_amount * item.place_price;
                }
                else
                {
                    msg = "此商品不存在，无法下单";
                    break;
                }
            }

            if (!isBuild)
                return new Tuple<bool, string, string>(false, "", msg);

            long order_id = OrderDataAccess.Instance.CreateOrderMaster(uid, model.addressid, model.invoice_id, orderno, model.pay_type, model.total_money, order_source, model.remark, out stroutput);
            if (order_id > 0)
            {
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                dbcontext.ADZ_PlaceOrderRel.Add(new ADZ_PlaceOrderRel
                {
                    create_time = DateTime.Now,
                    order_id = order_id,
                    place_id = place_id

                });
                dbcontext.SaveChanges();

                //循环插入商品从表
                int succCount = 0;
                foreach (var item in model.goodlist)
                {
                    int ret = OrderDataAccess.Instance.CreateYureOrderDetails(order_id, item.goods_id, item.place_amount, item.place_price, out stroutput);
                    if (ret < 0)
                    {
                        LogHelper.Error(stroutput);
                        break;
                    }
                    else
                        succCount++;
                }

                //关联预热订单和支付订单
                if (succCount == model.goodlist.Count)
                {

                    OrderInfo order = OrderDataAccess.Instance.GetOrderInfo(orderno);
                    var data = new
                    {
                        order_id = order_id,
                        order_no = orderno,
                        pay_end_time = order.pay_end_time,
                        total_money = order.total_money,
                        receiver = order.receiver,
                        receiver_telephone = order.receiver_telephone,
                        address_desc = order.address_desc
                    };

                    return new Tuple<bool, string, string>(true, JsonHelper.Serialize(data), orderno);
                }
                else
                    return new Tuple<bool, string, string>(false, "", stroutput);
            }
            else
            {
                LogHelper.Error(stroutput);
                return new Tuple<bool, string, string>(false, "", stroutput);
            }
        }
        /// <summary>
        /// 创建竞价成功转交易订单
        /// order_source 0 用户购物车下单 11 预订成功后系统下单 12 竞价成功后系统下单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string, string> CreateJingjiaOrder(long jingjia_id)
        {
            string stroutput = string.Empty;
            string orderno = BuidTradeOrder();
            string remark = "竞价成功后系统下单";
            string msg = string.Empty;


            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var jingjia_master = dbcontext.ADZ_JingjiaMaster.FirstOrDefault(t => t.jingjia_id == jingjia_id && t.is_del == 0 && t.jingjia_deal_status == 2);
            remark = $"竞价【{jingjia_master.jingjia_name}】成交，自动下单。";
            if (jingjia_master == null)
                return new Tuple<bool, string, string>(false, "", "竞价信息有误，无法下单");
            //获取最后报价的人
            var jingjia_submit = dbcontext.ADZ_JingjiaSubmit
                        .OrderByDescending(t => t.seq_id)
                        .FirstOrDefault(t => t.jingjia_id == jingjia_id && t.is_del == 0);
            if (jingjia_submit == null)
            {
                //发送业务消息
                BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                {
                    BusinessMsgType = (int)BusinessMsgEnum.UserCreateOrder,
                    msg = $"竞价【{jingjia_master.jingjia_name}】结束，没有用户参与竞价，已流拍。",
                    msg_title = "竞价结束",
                    msg_url = $"/jingjia/getlist/"
                });
                return new Tuple<bool, string, string>(true, "", "竞价流拍，无需下单");
            }

            if (jingjia_submit != null && jingjia_submit.status == 0)
            {
                jingjia_submit.is_hit = 1;
                jingjia_submit.status = 2;
                dbcontext.SaveChanges();

                var userinfo = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == jingjia_submit.uid);
                //发送业务消息
                BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                {
                    BusinessMsgType = (int)BusinessMsgEnum.UserCreateOrder,
                    msg = $"竞价【{jingjia_master.jingjia_name}】结束，用户【{userinfo.member_name}-{userinfo.account_mobile}】成交,成交金额：￥{jingjia_submit.my_price}",
                    msg_title = "竞价成交",
                    msg_url = $"/jingjia/getlist/"
                });

                //发送推送消息
                AddPushMsgModel paramModel = new AddPushMsgModel
                {
                    aDZ_Pushmessage = new ADZ_Pushmessage
                    {
                        MsgType = 2,
                        ReceiveType = 1,
                        MsgTitle = "竞价成交",
                        MsgText = $"恭喜您，您参与的竞价【{jingjia_master.jingjia_name}】已成交，成交金额：￥{jingjia_submit.my_price}。"
                    },
                    ReceiveUids = userinfo.uid.ToString()
                };
                PushMsgBiz.Instance.AddPushMsg(paramModel);

            }
            long uid = jingjia_submit.uid;
            //成交的需要开始创建订单
            if (jingjia_submit.status == 2 && jingjia_submit.is_hit == 1 && jingjia_submit.order_master_id == 0)
            {
                //1、获取默认的地址信息
                var addressinfo = dbcontext.ADZ_UserAddress
                    .OrderByDescending(t => t.is_default)
                    .OrderByDescending(t => t.seq_id)
                    .FirstOrDefault(t => t.uid == jingjia_submit.uid);

                int order_source = 12;
                int pay_type = 0;
                long invoice_id = 0;
                long addressid = 0;
                if (addressinfo != null)
                    addressid = addressinfo.seq_id;


                long order_id = OrderDataAccess.Instance.CreateOrderMaster(uid, addressid, invoice_id, orderno, pay_type, jingjia_submit.my_price, order_source, remark, out stroutput);
                if (order_id > 0)
                {
                    jingjia_submit.order_master_id = order_id;
                    dbcontext.SaveChanges();

                    //2、获取商品列表循环入库
                    var goods_ids = (
                        from t in dbcontext.ADZ_GoodsJingjia.Where(t => t.jingjia_id == jingjia_id)
                        select t.goods_id).ToList();
                    //循环插入商品从表
                    int succCount = 0;
                    foreach (var item in goods_ids)
                    {
                        int ret = OrderDataAccess.Instance.CreateOrderDetailsJingjia(order_id, item, out stroutput);
                        if (ret < 0)
                        {
                            LogHelper.Error(stroutput);
                            break;
                        }
                        else
                        {
                            succCount++;
                        }
                    }


                    OrderInfo order = OrderDataAccess.Instance.GetOrderInfo(orderno);
                    var data = new
                    {
                        order_no = orderno,
                        pay_end_time = order.pay_end_time,
                        total_money = order.total_money,
                        receiver = order.receiver,
                        receiver_telephone = order.receiver_telephone,
                        address_desc = order.address_desc,
                        create_time = order.create_time
                    };

                    //发送业务消息
                    BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                    {
                        BusinessMsgType = (int)BusinessMsgEnum.UserCreateOrder,
                        msg = $"竞价【{jingjia_master.jingjia_name}】结束，下单成功，订单号{order.order_NO},订单金额：￥{order.total_money}",
                        msg_title = "竞价成交下单",
                        msg_url = $"/OrderMaster/OrderMasterInfo/{order.order_id}"
                    });

                    //发送推送消息
                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "订单提交成功",
                            MsgText = $"您参与的竞价【{jingjia_master.jingjia_name}】成交订单{order.order_NO}已创建成功，请在【我的订单】查看，并请在24小时内完成付款，订单金额：￥{order.total_money}。"
                        },
                        ReceiveUids = uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(paramModel);

                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = order_id,
                        opmsg = "提交订单-竞价结束，用户成交",
                        op_user = "system"
                    });

                    return new Tuple<bool, string, string>(true, JsonHelper.Serialize(data), "");
                }
            }
            return new Tuple<bool, string, string>(false, "", "成交下单失败");
        }
        /// <summary>
        /// 生成交易订单号
        /// </summary>
        /// <returns></returns>
        public string BuidTradeOrder()
        {
            string orderno = "";
            string stroutput = string.Empty;
            long ret = OrderDataAccess.Instance.IdCreate("oid", out stroutput);
            if (ret > 0)
                orderno = DateTime.Now.ToString("yyMMddHHmm") + ret.ToString();
            return orderno;
        }

        /// <summary>
        /// 创建交易订单
        /// order_source 0 用户购物车下单 11 预订成功后系统下单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string, string> CreateOrder(long uid, int order_source, CreateOrderReq model)
        {
            if (uid <= 0)
                return new Tuple<bool, string, string>(false, "", "用户不存在，无法下单");

            string stroutput = string.Empty;
            string orderno = BuidTradeOrder();
            if (string.IsNullOrWhiteSpace(orderno))
                return new Tuple<bool, string, string>(false, "", "订单号生成失败，无法下单");

            string remark = string.Empty;
            string msg = string.Empty;
            if (order_source == 0)
                remark = "用户购物车下单";
            else if (order_source == 11)
                remark = "预订成功后系统下单";
            else
                return new Tuple<bool, string, string>(false, "", "订单来源错误，无法下单");

            var acc = AccountDataAccess.Instance.GetAccount(uid);
            if (acc == null)
                return new Tuple<bool, string, string>(false, "", "用户不存在，无法下单");

            //有价格商品才能下单（不管是直播还是预热商品）
            bool isBuild = false;
            decimal allMoney = 0;
            int include_tax = 10;
            foreach (var item in model.goodlist)
            {
                if (item.shoppingcart_id <= 0 || item.goods_id <= 0 || item.amount <= 0 || item.total_money <= 0)
                {
                    msg = "请求数据非法，无法下单";
                    break;
                }
                //验证购物车商品是否存在
                var cartResult = ShoppingCartBiz.Instance.GetInfo(uid, item.shoppingcart_id);
                if (!cartResult.Item1)
                {
                    msg = "购物车商品不存在，无法下单";
                    break;
                }

                //验证商品信息
                var result = GoodsBiz.Instance.GetGoods(item.goods_id);
                if (!result.Item1)
                {
                    msg = "此商品不存在，无法下单";
                    break;
                }
                #region 丢弃---含税与不含税都可以下单使用在线支付 2019-12-22 leev
                ////含税和未税不能一起下单 20190329 daneel
                //if (include_tax == 10)
                //    include_tax = result.Item2.include_tax;
                //else
                //{
                //    if (include_tax != result.Item2.include_tax)
                //    {
                //        msg = "由于含税部分需要开票，无法合并支付，请分开结算";
                //        break;
                //    }
                //}
                #endregion

                //判断会员等级是否能够购买此商品
                if (result.Item2.show_min_level > acc.member_level)
                {
                    msg = "会员等级不足，无法下单";
                    break;
                }

                if (item.amount > result.Item2.stock_amount)
                {
                    msg = "此商品库存不足，无法下单";
                    break;
                }
                if (item.amount < result.Item2.min_amount)
                {
                    msg = "此商品购买数量不能低于最小出库量，无法下单";
                    break;
                }
                if (result.Item2.price <= 0)
                {
                    msg = "此商品暂无价格，无法下单";
                    break;
                }

                //增加美元业务判断 by leev 2019-04-01
                if (result.Item2.currency_type == (int)CurrencyType.Dollar)
                {
                    msg = "美元业务价格面议，无法下单";
                    break;
                }

                //判断结束时间
                if (result.Item2.end_time != DateTime.MinValue)
                {
                    if (result.Item2.end_time.CompareTo(DateTime.Now) < 0)
                    {
                        msg = $"商品{result.Item2.MPN}已失效，无法下单";
                        break;
                    }
                }

                isBuild = true;
                allMoney += Utils.MathRound(result.Item2.price * item.amount * (1 + acc.add_rate), 2);
            }

            if (!isBuild)
                return new Tuple<bool, string, string>(false, "", msg);
            model.total_money = Utils.MathRound(model.total_money, 2);
            if (Math.Abs(allMoney - model.total_money) > 1)
            {
                LogHelper.Error(string.Format("提交订单-商品总金额有误，allMoney：{0} total_money：{1}", allMoney, model.total_money));
                return new Tuple<bool, string, string>(false, "", "商品总金额有误，无法下单");
            }

            long order_id = OrderDataAccess.Instance.CreateOrderMaster(uid, model.addressid, model.invoice_id, orderno, model.pay_type, model.total_money, 0, model.remark, out stroutput);
            if (order_id > 0)
            {
                //循环插入商品从表
                int succCount = 0;
                foreach (var item in model.goodlist)
                {
                    int ret = OrderDataAccess.Instance.CreateOrderDetails(order_id, item.goods_id, item.amount, item.total_money, out stroutput);
                    if (ret < 0)
                    {
                        LogHelper.Error(stroutput); break;
                    }
                    else
                    {
                        //清除购物车商品
                        ShoppingCartBiz.Instance.Del(item.shoppingcart_id);
                        succCount++;
                    }
                }

                if (succCount == model.goodlist.Count)
                {
                    OrderInfo order = OrderDataAccess.Instance.GetOrderInfo(orderno);
                    var data = new
                    {
                        order_no = orderno,
                        pay_end_time = order.pay_end_time,
                        total_money = order.total_money,
                        receiver = order.receiver,
                        receiver_telephone = order.receiver_telephone,
                        address_desc = order.address_desc,
                        create_time = order.create_time
                    };

                    Task.Run(() =>
                    {
                        string mobile_msg = $"用户{acc.account_mobile}下单成功，订单号{order.order_NO},订单金额：￥{model.total_money}";
                        //发送业务消息
                        BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                        {
                            BusinessMsgType = (int)BusinessMsgEnum.UserCreateOrder,
                            msg = mobile_msg,
                            msg_title = "用户下单",
                            msg_url = $"/OrderMaster/OrderMasterInfo/{order.order_id}"
                        });

                        BusinessMsgBiz.Instance.SendMobileMsg(mobile_msg);

                        //发送推送消息
                        AddPushMsgModel paramModel = new AddPushMsgModel
                        {
                            aDZ_Pushmessage = new ADZ_Pushmessage
                            {
                                MsgType = 2,
                                ReceiveType = 1,
                                MsgTitle = "订单提交成功",
                                MsgText = $"您的订单{order.order_NO}已提交成功，请尽快付款，订单金额：￥{model.total_money}。"
                            },
                            ReceiveUids = uid.ToString()
                        };
                        PushMsgBiz.Instance.AddPushMsg(paramModel);

                        OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                        {
                            order_id = order_id,
                            opmsg = "提交订单-用户",
                            op_user = uid.ToString()
                        });

                    });

                    return new Tuple<bool, string, string>(true, JsonHelper.Serialize(data), "");
                }
                else
                    return new Tuple<bool, string, string>(false, "", stroutput);
            }
            else
            {
                LogHelper.Error(stroutput);
                return new Tuple<bool, string, string>(false, "", stroutput);
            }
        }

        /// <summary>
        /// 支付交易订单
        /// </summary>
        public Tuple<bool, string, string> PayOrder(long uid, string paypwd, string order_no, decimal amt, int pay_type)
        {
            string strResp = string.Empty;
            //判断用户
            var acc = AccountDataAccess.Instance.GetAccount(uid);
            if (acc == null)
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，用户不存在");

            if (acc.account_status != (int)AccountStatus.Normal)
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，用户异常");


            //判断支付密码
            if (pay_type == (int)PayType.Balance)
            {
                if (string.IsNullOrWhiteSpace(acc.pay_password))
                    return new Tuple<bool, string, string>(false, strResp, "订单支付失败，未设置支付密码");

                var checkResult = AccountBiz.Instance.CheckPayPwd(uid, acc.pay_password, paypwd);
                if (!checkResult.Item1)
                    return new Tuple<bool, string, string>(false, strResp, checkResult.Item2);
            }

            //判断订单
            OrderMaster order = OrderDataAccess.Instance.GetOrderMaster(order_no);
            if (order == null)
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，订单不存在");

            if (order.order_status != (short)OrderStatus.WaitPay)
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，订单处理中");

            if (order.pay_type == (short)PayType.UnderLine)
                return new Tuple<bool, string, string>(false, strResp, "订单只能线下支付");

            //判断支付金额
            if (order.total_money != amt)
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，支付金额错误");

            //判断是否超过支付结束时间
            if (order.pay_end_time != DateTime.MinValue)
            {
                if (order.pay_end_time < DateTime.Now)
                    return new Tuple<bool, string, string>(false, strResp, "超过支付时间，不能支付");
            }

            PayOrderResp resp = new PayOrderResp();
            resp.amt = amt;
            resp.order_no = order_no;
            resp.pay_type = pay_type;
            resp.respData = "";
            if (pay_type == (int)PayType.Balance)
            {
                //余额支付，验证余额是否足够支付
                if (acc.account_balance < amt)
                    return new Tuple<bool, string, string>(false, strResp, "订单支付失败，余额不足");

                //支付-账户扣钱，修改交易订单状态等
                if (!OrderPaySucc(order.order_id, pay_type))
                {
                    return new Tuple<bool, string, string>(false, strResp, "支付失败");
                }
            }
            else if (pay_type == (int)PayType.Alipay)
            {
                //创建充值订单
                string zfbOrderId = Utils.BuildOrderId("CH", 20);
                string zfbBillNo = Utils.BuildOrderId("", 20);
                if (!CreateChargeOrder(zfbOrderId, zfbBillNo, uid, (int)BusinessOrderType.SaleOrder, order.order_id, amt, (int)ChannelType.AlipayApp, "支付宝app充值"))
                    return new Tuple<bool, string, string>(false, strResp, "订单支付失败，创建充值订单失败");

                //提交支付宝充值
                var zfbResult = AlipayBiz.DoSubmit(zfbBillNo, amt);
                if (!zfbResult.Item1)
                    return new Tuple<bool, string, string>(false, strResp, zfbResult.Item3);

                resp.respData = zfbResult.Item2;
            }
            else if (pay_type == (int)PayType.Wechat)
            {
                //创建充值订单
                string wxOrderId = Utils.BuildOrderId("CH", 20);
                string wxBillNo = Utils.BuildOrderId("", 20);
                if (!CreateChargeOrder(wxOrderId, wxBillNo, uid, (int)BusinessOrderType.SaleOrder, order.order_id, amt, (int)ChannelType.WechatApp, "微信app充值"))
                    return new Tuple<bool, string, string>(false, strResp, "订单支付失败，创建充值订单失败");

                //提交微信充值
                var wxResult = WechatBiz.BuildOrder(wxBillNo, amt);
                if (!wxResult.Item1)
                    return new Tuple<bool, string, string>(false, strResp, wxResult.Item3);

                resp.respData = wxResult.Item2;
            }
            else
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，支付方式错误");

            strResp = JsonHelper.Serialize(resp);
            return new Tuple<bool, string, string>(true, strResp, "");
        }

        /// <summary>
        /// 订单详情
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, OrderInfoModel> GetOrder(string order_no)
        {
            //订单主表信息
            OrderInfo order = OrderDataAccess.Instance.GetOrderInfo(order_no);
            if (order == null || order.order_id == 0)
                return new Tuple<bool, OrderInfoModel>(false, null);

            //订单商品
            List<OrderGood> goodlist = OrderDataAccess.Instance.GetOrderGood(order.order_id);
            if (goodlist == null)
                goodlist = new List<OrderGood>();

            foreach (var item in goodlist)
            {
                item.imglist = GoodsBiz.Instance.GetGoodsIMG(item.goods_id, true);
            }

            string strJson = JsonHelper.SerializeNoSetting(order);
            OrderInfoModel model = JsonHelper.Deserialize<OrderInfoModel>(strJson);
            model.goodlist = goodlist;
            return new Tuple<bool, OrderInfoModel>(true, model);
        }


        /// <summary>
        /// 我的订单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, OrderListModel> GetOrderList(long uid, int order_status, int pageIndex, int pageRows)
        {
            DataSet ds = OrderDataAccess.Instance.GetOrderList(uid, order_status, pageIndex, pageRows);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                OrderListModel model = new OrderListModel();
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);
                model.list = new ModelHandler<OrderInfoModel>().FillModel(ds.Tables[1]);


                //通过循环赋值订单商品信息
                foreach (var item in model.list)
                {
                    List<OrderGood> goodlist = OrderDataAccess.Instance.GetOrderGood(item.order_id);
                    if (goodlist != null)
                    {
                        foreach (var item2 in goodlist)
                        {
                            item2.imglist = GoodsBiz.Instance.GetGoodsIMG(item2.goods_id, true);
                        }
                        item.goodlist = goodlist;
                    }
                    else
                    {
                        item.goodlist = new List<OrderGood>();
                    }
                }
                return new Tuple<bool, OrderListModel>(true, model);
            }
            else
                return new Tuple<bool, OrderListModel>(false, null);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> CancelOrder(string order_no, int op_type = 0)
        {
            //判断订单
            OrderMaster order = OrderDataAccess.Instance.GetOrderMaster(order_no);
            if (order == null)
                return new Tuple<bool, string>(false, "取消订单失败，此订单不存在");

            //只有待付款订单可以取消
            if (order.order_status != (short)OrderStatus.WaitPay)
                return new Tuple<bool, string>(false, "此订单在处理中，无法取消");
            //此类操作不能取消以下情况的订单
            if (op_type == 0)
            {
                //预定后系统生成的订单不可取消
                if (order.order_source == 11)
                    return new Tuple<bool, string>(false, "此订单为您预定报价的订单，无法取消");
                if (order.order_source == 12)
                    return new Tuple<bool, string>(false, "此订单为竞价成交的订单，无法取消");
                if (order.order_source > 10)
                    return new Tuple<bool, string>(false, "此订单无法取消,请联系客服。");
            }

            if (UpdateOrderStatus(order_no, order.order_status, (int)OrderStatus.Cancel))
            {
                //支付订单取消的话竞拍订单也要取消
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                var jingjia_submit = dbcontext.ADZ_JingjiaSubmit.FirstOrDefault(t => t.order_master_id == order.order_id);
                if (jingjia_submit != null && jingjia_submit.status == 2)
                {
                    jingjia_submit.status = 11;
                    dbcontext.SaveChanges();
                }
                //订单取消成功，恢复库存
                var orderGoods = OrderDataAccess.Instance.GetOrderGood(order.order_id);
                foreach (var item in orderGoods)
                {
                    //开始恢复库存
                    if (!GoodsBiz.Instance.AddStockAmount(item.goods_id, item.buy_amount))
                    {
                        LogHelper.Error("取消订单-恢复库存失败," + JsonHelper.Serialize(item));
                    }
                }

                //发送推送消息
                AddPushMsgModel paramModel = new AddPushMsgModel
                {
                    aDZ_Pushmessage = new ADZ_Pushmessage
                    {
                        MsgType = 2,
                        ReceiveType = 1,
                        MsgTitle = "订单关闭",
                        MsgText = $"您的订单{order_no}已成功关闭，如要支付请重新下单。"
                    },
                    ReceiveUids = order.uid.ToString()
                };
                PushMsgBiz.Instance.AddPushMsg(paramModel);
                OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                {
                    order_id = order.order_id,
                    opmsg = "订单关闭"
                });

                return new Tuple<bool, string>(true, "");
            }
            else
                return new Tuple<bool, string>(false, "此订单取消失败");
        }

        /// <summary>
        /// 确认收货
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> ConfirmOrder(string order_no)
        {
            //判断订单
            OrderMaster order = OrderDataAccess.Instance.GetOrderMaster(order_no);
            if (order == null)
                return new Tuple<bool, string>(false, "确认收货失败，此订单不存在");

            if (UpdateOrderStatus(order_no, order.order_status, (int)OrderStatus.Complete))
            {
                OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                {
                    order_id = order.order_id,
                    opmsg = "确认收货"
                });

                return new Tuple<bool, string>(true, "");
            }
            else
                return new Tuple<bool, string>(false, "此订单确认收货失败");
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> DelOrder(string order_no)
        {
            //判断订单
            OrderMaster order = OrderDataAccess.Instance.GetOrderMaster(order_no);
            if (order == null)
                return new Tuple<bool, string>(false, "删除订单失败，此订单不存在");

            //只有已取消订单可以删除
            if (order.order_status != (short)OrderStatus.Cancel)
                return new Tuple<bool, string>(false, "此订单在处理中，无法删除");

            if (OrderDataAccess.Instance.DelOrder(order_no) > 0)
            {
                OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                {
                    order_id = order.order_id,
                    opmsg = "删除订单"
                });
                return new Tuple<bool, string>(true, "");
            }
            else
                return new Tuple<bool, string>(false, "此订单删除失败");
        }

        /// <summary>
        /// 上传付款凭证
        /// </summary>
        public Tuple<bool, string, string> UpPayImg(string order_no, string img_data, string filetype)
        {
            //订单主表信息
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var order = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_NO == order_no && t.is_del == 0);
            if (order == null || order.order_id == 0)
                return new Tuple<bool, string, string>(false, "上传付款凭证，订单不存在", "");

            if (order.pay_type != 0)
                return new Tuple<bool, string, string>(false, "线下支付才需上传付款凭证", "");

            //上传图片至阿里云
            var result = ImageFileBiz.UpImg(img_data, filetype, "payimg");
            if (!result.Item1)
                return new Tuple<bool, string, string>(false, result.Item2, "");

            order.pay_img_url = result.Item3;
            dbcontext.SaveChanges();
            OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
            {
                order_id = order.order_id,
                opmsg = "用户上传支付凭证"
            });

            return new Tuple<bool, string, string>(true, "", AliyunOssBiz.GetImg(result.Item3));
        }


        /// <summary>
        /// 获取付款凭证
        /// </summary>
        public string LoadPayImg(string order_no)
        {
            string img_url = "";
            //订单主表信息
            OrderInfo order = OrderDataAccess.Instance.GetOrderInfo(order_no);
            if (order != null && order.order_id > 0)
            {
                if (!string.IsNullOrWhiteSpace(order.pay_img_url))
                    img_url = AliyunOssBiz.GetImg(order.pay_img_url);
            }
            return img_url;
        }

        /// <summary>
        /// 上传发票资料
        /// </summary>
        public Tuple<bool, string, string> UpInvoiceImg(string order_no, string img_data, string filetype)
        {
            //订单主表信息
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var order = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_NO == order_no && t.is_del == 0);
            if (order == null || order.order_id == 0)
                return new Tuple<bool, string, string>(false, "上传发票资料，订单不存在", "");

            if (order.pay_type != 0)
                return new Tuple<bool, string, string>(false, "线下支付才需上传发票资料", "");

            //上传图片至阿里云
            var result = ImageFileBiz.UpImg(img_data, filetype, "invoiceimg");
            if (!result.Item1)
                return new Tuple<bool, string, string>(false, result.Item2, "");

            long order_id = order.order_id;
            var orderInvoiceRel = dbcontext.ADZ_OrderInvoiceRel.FirstOrDefault(t => t.order_id == order_id);
            if (orderInvoiceRel == null)
            {
                ADZ_OrderInvoiceRel aDZ_OrderInvoiceRel = new ADZ_OrderInvoiceRel
                {
                    order_id = order_id,
                    invoice_img = result.Item3,
                    is_ready = 0,
                    invoice_type = 1,
                    create_time = DateTime.Now
                };
                dbcontext.ADZ_OrderInvoiceRel.Add(aDZ_OrderInvoiceRel);
            }
            else
            {
                orderInvoiceRel.invoice_img = result.Item3;
            }
            dbcontext.SaveChanges();
            OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
            {
                order_id = order.order_id,
                opmsg = "用户上传发票资料"
            });

            return new Tuple<bool, string, string>(true, "", AliyunOssBiz.GetImg(result.Item3));
        }

        /// <summary>
        /// 获取发票资料
        /// </summary>
        public string LoadInvoiceImg(string order_no)
        {
            string img_url = "";
            //订单主表信息
            OrderInfo order = OrderDataAccess.Instance.GetOrderInfo(order_no);
            if (order != null && order.order_id > 0)
            {
                if (!string.IsNullOrWhiteSpace(order.invoice_img))
                    img_url = AliyunOssBiz.GetImg(order.invoice_img);
            }
            return img_url;
        }

        /// <summary>
        /// 快递实时查询
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string, ExpressQueryResp> ExpressQuery(long uid, string order_no)
        {
            //订单主表信息
            OrderInfo order = OrderDataAccess.Instance.GetOrderInfo(order_no);
            if (order != null && order.order_id > 0)
            {
                if (!(order.order_status == (short)OrderStatus.Complete || order.order_status == (short)OrderStatus.PaySucc))
                    return new Tuple<bool, string, ExpressQueryResp>(false, "订单状态错误", null);

                if (uid != order.uid)
                    return new Tuple<bool, string, ExpressQueryResp>(false, "不能查看他人物流信息", null);

                string num = order.express_NO;
                string com = order.express_com;
                string phone = order.receiver_telephone;
                if (string.IsNullOrEmpty(num) || string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(com))
                    return new Tuple<bool, string, ExpressQueryResp>(false, "商品还未寄出，请稍后查询", null);

                //开始请求快递110接口查询
                var result = ExpressBiz.Query(com, num, phone);

                //通过快递公司编号获取名称
                if (result.Item1)
                {
                    ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                    var express = dbcontext.ADZ_ExpressConfig.FirstOrDefault(t => t.express_com == result.Item3.com);
                    result.Item3.express_name = express == null ? "" : express.express_name;
                }
                return result;
            }
            else
                return new Tuple<bool, string, ExpressQueryResp>(false, "订单不存在", null);
        }

        /// <summary>
        /// 交易订单状态修改
        /// </summary>
        /// <param name="order_no"></param>
        /// <param name="old_status"></param>
        /// <param name="new_status"></param>
        /// <returns></returns>
        public bool UpdateOrderStatus(string order_no, int old_status, int new_status)
        {
            bool isUpdate = false;
            switch (new_status)
            {
                case (int)OrderStatus.PaySucc:
                    if (old_status == (int)OrderStatus.WaitPay) isUpdate = true;
                    break;
                case (int)OrderStatus.Complete:
                    if (old_status == (int)OrderStatus.PaySucc) isUpdate = true;
                    break;
                case (int)OrderStatus.Cancel:
                    if (old_status == (int)OrderStatus.WaitPay) isUpdate = true;
                    break;
            }

            if (isUpdate)
            {
                int ret = OrderDataAccess.Instance.UpdateOrderStatus(order_no, old_status, new_status);
                if (ret > 0)
                    isUpdate = true;
                else
                    isUpdate = false;
            }
            else
                LogHelper.Error(string.Format("交易订单状态不能从{0}直接修改为{1}", old_status, new_status));
            return isUpdate;
        }

        /// <summary>
        /// 获取用户销售/服务费用
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="begtime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public DataTable GetSaleAmt(long uid, DateTime begtime, DateTime endtime)
        {
            DataTable dt = null;
            if (begtime == endtime)
                endtime = endtime.AddDays(1);

            dt = OrderDataAccess.Instance.GetSaleAmt(uid, begtime.ToString("yyyy-MM-dd"), endtime.ToString("yyyy-MM-dd"));
            return dt;
        }

        /// <summary>
        /// 获取用户推荐费用
        /// </summary>
        /// <returns></returns>
        public decimal GetRecommendAmt(long uid, DateTime begtime, DateTime endtime)
        {
            decimal recommendAmt = 0;
            if (begtime == endtime)
                endtime = endtime.AddDays(1);

            DataTable dt = OrderDataAccess.Instance.GetRecommendAmt(uid, begtime.ToString("yyyy-MM-dd"), endtime.ToString("yyyy-MM-dd"));
            if (dt != null && dt.Rows.Count > 0)
            {
                recommendAmt = ConvertHelper.ConvertTo<decimal>(dt.Rows[0]["recommendAmt"]);
            }

            return recommendAmt;
        }
        #endregion

        #region 预定商品报价
        /// <summary>
        /// 修改预定报价状态
        /// </summary>
        /// <param name="seq_id"></param>
        /// <param name="old_status"></param>
        /// <param name="new_status"></param>
        /// <returns></returns>
        public bool UpdatePlaceStatus(long seq_id, int old_status, int new_status)
        {
            bool isUpdate = false;
            switch (new_status)
            {
                case (int)PlaceStatus.WaitPay:
                    if (old_status == (int)PlaceStatus.Placeing) isUpdate = true;
                    break;
                case (int)PlaceStatus.Complete:
                    if (old_status == (int)PlaceStatus.WaitPay) isUpdate = true;
                    break;
                case (int)PlaceStatus.Cancel:
                    if (old_status == (int)PlaceStatus.Placeing) isUpdate = true;
                    break;
            }

            if (isUpdate)
            {
                int ret = OrderDataAccess.Instance.UpdatePlaceStatus(seq_id, old_status, new_status);
                if (ret > 0)
                    isUpdate = true;
                else
                    isUpdate = false;
            }
            else
                LogHelper.Error(string.Format("预定商品报价状态不能从{0}直接修改为{1}", old_status, new_status));
            return isUpdate;
        }

        /// <summary>
        /// 取消报价
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> CancelGoodsPlace(long seq_id)
        {
            GoodsPlace place = OrderDataAccess.Instance.GetGoodsPlace(seq_id);
            if (place == null)
                return new Tuple<bool, string>(false, "取消报价失败，此报价不存在");


            if (UpdatePlaceStatus(seq_id, place.place_status, (int)PlaceStatus.Cancel))
                return new Tuple<bool, string>(true, "");
            else
                return new Tuple<bool, string>(false, "此报价取消失败");
        }

        /// <summary>
        /// 删除预定报价
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> DelGoodsPlace(long seq_id)
        {
            GoodsPlace place = OrderDataAccess.Instance.GetGoodsPlace(seq_id);
            if (place == null)
                return new Tuple<bool, string>(false, "此报价不存在，无法删除");

            if (place.place_status == (int)PlaceStatus.Complete || place.place_status == (int)PlaceStatus.WaitPay)
                return new Tuple<bool, string>(false, "此报价处理中，无法删除");

            if (OrderDataAccess.Instance.DelGoodsPlace(seq_id) > 0)
                return new Tuple<bool, string>(true, "");
            else
                return new Tuple<bool, string>(false, "此报价删除失败");
        }

        /// <summary>
        /// 预定商品报价
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> GoodsPlaceBuild(long uid, long goods_id, decimal place_price)
        {
            if (uid <= 0)
                return new Tuple<bool, string>(false, "预定商品报价失败，用户不存在");

            string stroutput = string.Empty;
            long ret = OrderDataAccess.Instance.CreateGoodsPlace(uid, goods_id, place_price, out stroutput);
            if (ret > 0)
                return new Tuple<bool, string>(true, "");
            else
                return new Tuple<bool, string>(false, stroutput);
        }

        /// <summary>
        /// 获取报价
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, decimal, string> GetGoodsPlace(long uid, long goods_id)
        {
            if (uid <= 0)
                return new Tuple<bool, decimal, string>(false, 0, "获取报价失败，用户不存在");

            DataTable dt = OrderDataAccess.Instance.GetGoodsPlace(uid, goods_id);
            if (dt != null && dt.Rows.Count > 0)
                return new Tuple<bool, decimal, string>(true, ConvertHelper.ConvertTo<decimal>(dt.Rows[0]["place_price"]), dt.Rows[0]["place_status"].ToString());
            else
                return new Tuple<bool, decimal, string>(false, 0, "获取报价失败，报价不存在");
        }

        /// <summary>
        /// 我的预定
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, PlaceListModel> GetPlaceList(long uid, int place_status, int pageIndex, int pageRows)
        {
            if (uid <= 0)
                return new Tuple<bool, PlaceListModel>(false, null);

            DataSet ds = OrderDataAccess.Instance.GetPlaceList(uid, place_status, pageIndex, pageRows);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                PlaceListModel model = new PlaceListModel();
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);
                model.list = new ModelHandler<GoodsPlaceModel>().FillModel(ds.Tables[1]);

                //图片处理
                foreach (var item in model.list)
                {
                    item.imglist = GoodsBiz.Instance.GetGoodsIMG(item.goods_id, true);
                }

                return new Tuple<bool, PlaceListModel>(true, model);
            }
            else
                return new Tuple<bool, PlaceListModel>(false, null);
        }
        #endregion

        #region 销售业绩
        /// <summary>
        /// 根据供应商统计订单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, OrderBySupplierList> GetOrderBySupplier(long supplier_id, string supplier_name, string beg_date, string end_date, int pageIndex, int pageRows)
        {
            if (!string.IsNullOrEmpty(end_date))
                end_date = ConvertHelper.ConvertTo<DateTime>(end_date).AddDays(1).ToString("yyyy-MM-dd");

            DataSet ds = OrderDataAccess.Instance.GetOrderBySupplier(supplier_id, supplier_name, beg_date, end_date, pageIndex, pageRows);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                OrderBySupplierList model = new OrderBySupplierList();
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);
                model.allmoney = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allmoney"]);
                model.list = new ModelHandler<OrderBySupplier>().FillModel(ds.Tables[1]);

                return new Tuple<bool, OrderBySupplierList>(true, model);
            }
            else
                return new Tuple<bool, OrderBySupplierList>(false, null);
        }

        /// <summary>
        /// 按日期结算销售费用
        /// </summary>
        /// <param name="saledate">结算日期</param>
        /// <returns></returns>
        public Tuple<bool, string> SaleSettlement(DateTime saledate)
        {
            string stroutput = string.Empty;

            long ret = OrderDataAccess.Instance.SaleSettlement(saledate.ToString("yyyy-MM-dd"), out stroutput);
            if (ret > 0)
                return new Tuple<bool, string>(true, "");
            else
                return new Tuple<bool, string>(false, stroutput);
        }
        /// <summary>
        /// 自动维护结算数据
        /// </summary>
        /// <returns></returns>
        public void SaleSettlementRepair()
        {
            string stroutput = string.Empty;

            long ret = OrderDataAccess.Instance.SaleSettlementRepair(out stroutput);
            if (!string.IsNullOrWhiteSpace(stroutput))
            {
                LogHelper.Error("自动维护结算数据发现异常：" + stroutput);
            }
        }

        /// <summary>
        /// 销售业绩查询
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="beg_saledate"></param>
        /// <param name="end_saledate"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageRows"></param>
        /// <returns></returns>
        public Tuple<bool, SaleSettlementListModel> GetSaleSettlementList(long uid, string beg_saledate, string end_saledate, int pageIndex, int pageRows)
        {
            if (beg_saledate == end_saledate)
                end_saledate = ConvertHelper.ConvertTo<DateTime>(end_saledate).AddDays(1).ToString("yyyy-MM-dd");

            DataSet ds = OrderDataAccess.Instance.GetSaleSettlementList(uid, beg_saledate, end_saledate, pageIndex, pageRows);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                SaleSettlementListModel model = new SaleSettlementListModel();
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);
                model.list = new ModelHandler<SaleSettlement>().FillModel(ds.Tables[1]);

                return new Tuple<bool, SaleSettlementListModel>(true, model);
            }
            else
                return new Tuple<bool, SaleSettlementListModel>(false, null);
        }
        #endregion

        #region 提现订单
        /// <summary>
        /// 创建提现订单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> CreateCashOrder(long uid, decimal cash_amt, long cash_bank_id)
        {
            string order_no = Utils.BuildOrderId("CA");
            if (uid <= 0 || cash_amt <= 0)
            {
                LogHelper.Error("提现失败,参数错误");
                return new Tuple<bool, string>(false, "提现失败,方法参数错误");
            }

            string orderResult = string.Empty;
            long orderRet = OrderDataAccess.Instance.CreateCashOrder(uid, order_no, cash_amt, cash_bank_id, out orderResult);
            if (orderRet > 0)
                return new Tuple<bool, string>(true, "");
            else
            {
                LogHelper.Error("创建提现订单失败：" + orderResult);
                return new Tuple<bool, string>(false, orderResult);
            }
        }
        #endregion

        #region 退款
        /// <summary>
        /// 创建退款订单
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> CreateRefundOrder(string order_no, int business_order_type, long order_master_id, decimal refund_amt, string refund_goods, string reason, string apply_user, string remark)
        {
            string stroutput = string.Empty;
            if (refund_amt <= 0)
            {
                return new Tuple<bool, string>(false, "退款金额不能为0");
            }

            long ret = OrderDataAccess.Instance.CreateRefundOrder(order_no, business_order_type, order_master_id, refund_amt, refund_goods, reason, apply_user, remark, out stroutput);
            if (ret > 0)
                return new Tuple<bool, string>(true, stroutput);
            else
                return new Tuple<bool, string>(false, stroutput);
        }

        /// <summary>
        /// 订单退款
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> RefundOrder(int business_order_type, long order_master_id, string refund_order_no, decimal refund_amt)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            long uid = 0;
            string order_no = "";
            byte pay_type = 0;
            string refund_name = "";
            if (business_order_type == (int)BusinessOrderType.SaleOrder)
            {
                refund_name = "销售订单退款";
                var order_master = dbcontext.View_Order.FirstOrDefault(t => t.order_id == order_master_id && t.is_succ == 1 && t.is_del == 0);
                if (order_master != null)
                {
                    if (order_master.is_apply_refund == 0)
                        return new Tuple<bool, string>(false, "无法退款，请先进行申请");

                    int order_status = (int)order_master.order_status;
                    if (!(order_status == (int)OrderStatus.PaySucc || order_status == (int)OrderStatus.Complete))
                        return new Tuple<bool, string>(false, "无法退款，销售订单已处理");

                    uid = order_master.uid.Value;
                    pay_type = order_master.pay_type.Value;
                    order_no = order_master.order_NO;
                }
                else
                {
                    return new Tuple<bool, string>(false, "退款订单不存在");
                }
            }
            else if (business_order_type == (int)BusinessOrderType.BaomingOrder)
            {
                refund_name = "竞价保证金退款";
                var baoming = dbcontext.ADZ_JingjiaBaomingOrder.FirstOrDefault(t => t.seq_id == order_master_id && t.is_succ == 1);
                if (baoming != null)
                {
                    if (baoming.is_apply_refund == 0)
                        return new Tuple<bool, string>(false, "无法退款，请先进行申请");
                    if (baoming.order_status >= 2)
                        return new Tuple<bool, string>(false, "无法退款，竞价报名订单已处理");

                    baoming.order_status = 2;
                    dbcontext.SaveChanges();
                }
                else
                {
                    return new Tuple<bool, string>(false, "退款订单不存在");
                }
                uid = baoming.uid;
                pay_type = baoming.pay_type;
                order_no = baoming.order_NO;
            }


            bool is_refund = false;
            string error_msg = string.Empty;

            //判断支付类型
            switch (pay_type)
            {
                case (int)PayType.Balance:
                    var chargeMember = dbcontext.ADZ_ChargeMaster.FirstOrDefault(t => t.uid == uid);
                    if (chargeMember != null)
                    {
                        //加钱
                        chargeMember.charge_balance += refund_amt;
                        chargeMember.account_balance += refund_amt;
                        dbcontext.SaveChanges();

                        //记录资金流水
                        AccountBiz.Instance.AddAmountLog((long)uid, refund_amt, (int)OrderType.OrderMasterRefund, order_no, 0, refund_name, refund_name, 0);

                        is_refund = true;
                    }
                    else
                        return new Tuple<bool, string>(false, "无法退款，账户不存在");
                    break;
                    
                case (int)PayType.Alipay:
                    var charge_order_alpay = dbcontext.ADZ_ChargeOrder.FirstOrDefault(t => t.order_master_id == order_master_id && t.uid == uid && t.business_order_type == business_order_type);
                    if (charge_order_alpay == null)
                        return new Tuple<bool, string>(false, "无法退款，支付方式不是支付宝支付");

                    var result = AlipayBiz.Refund(charge_order_alpay.billno, refund_amt);
                    is_refund = result.Item1;
                    if (!result.Item1)
                        error_msg = result.Item2;
                    break;
                case (int)PayType.Wechat:
                    var charge_order = dbcontext.ADZ_ChargeOrder.FirstOrDefault(t => t.order_master_id == order_master_id && t.uid == uid && t.business_order_type == business_order_type);
                    if (charge_order == null)
                        return new Tuple<bool, string>(false, "无法退款，支付方式不是微信支付");
                    string bill_no = charge_order.billno;
                    decimal amt = (decimal)charge_order.order_amt;
                    var result2 = WechatBiz.Refund(refund_order_no, bill_no, amt, refund_amt);
                    is_refund = result2.Item1;
                    if (!result2.Item1)
                        error_msg = result2.Item2;
                    break;
                case (int)PayType.UnderLine:
                    //线下支付退款请业务人员直接退款用户银行账号
                    is_refund = true;
                    break;
                    
            }
            is_refund = true;
            return new Tuple<bool, string>(is_refund, error_msg);
        }

        #endregion


        #region 同步AB系统的库存 async

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string, string> AsyncStock(List<GoodsModel> goodslist)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            foreach (var item in goodslist)
            {
                var view_goods = dbcontext.Views_Goods.FirstOrDefault(t =>
                     t.DCN == item.DCN
                     && t.MPN == item.MPN
                     && t.supplier_name == item.supplier_name
                     && t.brand_name == item.brand_name
                     && t.category_name == item.category_name
                 );
                if (view_goods != null && view_goods.stock_amount != item.stock_amount)
                {
                    var goods = dbcontext.ADZ_GoodsMaster.First(t => t.goods_id == view_goods.goods_id);
                    goods.stock_amount = item.stock_amount;

                    LogHelper.Info($"外部系统同步物料[{view_goods.goods_id}]库存：{view_goods.stock_amount}=>{item.stock_amount}");
                }
                dbcontext.SaveChanges();
            }
            return new Tuple<bool, string, string>(true, "", "");
        }

        #endregion
    }
}